"use strict";
const suiteDao = require("../dao/suite_dao");
const suiteToOrgDao = require("../dao/suite_to_org_dao");
const bossApi = require("../lib/boss_api");
const isvApp = require('../config/isv_app');

const updateSuiteTicket = function(req) {
	console.log("接收到ticket推送", req.body);
	const response = req.body;
	const suiteKey = response.suite_key;
	const update = {
		suiteTicket: response.param.suite_ticket,
		vendorKey: response.vendor_key
	};
	suiteDao.updateSuiteBySuiteKey(suiteKey, update);
};
const updateOrgTempCode = function(req) {
	/*
		接收到tempcode的时候，无需立即兑换，等到用户第一次请求接口的时候，再去检查和兑换
	*/
	/*{
		"event_type": "tmp_auth_code",
		"suite_key": "830dd1",
		"vendor_key": "8018301",
		"param": {
			"domain_id": "atwork",
			"org_code": "83201938013810",
			"tmp_auth_code": "授权码"
		}
	}*/
	console.log("接收到temp code推送", req.body);
	const response = req.body;
	const ctx = {
		domainId: response.param.domain_id,
		orgId: response.param.org_code
	};
	const suiteKey = response.suite_key;
	const tempAuthCode = response.param.tmp_auth_code;
	suiteToOrgDao.updateOrgTempCodeBySuiteKey.call(ctx, suiteKey, tempAuthCode);
	suiteToOrgDao.getSuiteToOrgBySuiteKey(req.body.suite_key).then(result => {
		bossApi.getPermanentCode({
			suiteKey: req.body.suite_key,
			suiteSecret: isvApp[req.body.suite_key],
			suiteTicket: result.suiteKey.suiteTicket,
			tempAuthCode: tempAuthCode,
			domainId: ctx.domainId,
			orgId: ctx.orgId
		})
	})
	
};
const updateSuiteTicketOrTempCode = function(req, res) {
	res.json({
		status: 0
	});
	if (req.body.event_type === "suite_ticket") {
		updateSuiteTicket(req, res);
	} else if (req.body.event_type === "tmp_auth_code") {
		updateOrgTempCode(req, res);
	} else {
		console.error("不支持的请求类型", req.body.event_type);
	}
};

const getPermanentCode = function(suite) {
	if (!suite.tempAuthCode) {
		console.error("没有临时授权码？！", suite);
		return Promise.reject(new Error("e_no_tcode"));
	} else if (!suite.permanentCode) {
		console.warn("没有永久码记录，将从boss平台兑换", suite);
		return bossApi.getPermanentCode(suite);
	} else {
		console.warn("取得的永久码是", suite);
		return Promise.resolve(suite.permanentCode);
	}
};

module.exports = {
	updateSuiteTicketOrTempCode,
	getPermanentCode
};